package com.bodystm.hardwarecavas;

import androidx.annotation.MainThread;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import butterknife.BindView;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.EventLog;
import android.util.Log;
import android.view.View;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

public class MainActivity extends AppCompatActivity {

    private String TAG = MainActivity.class.getName();

    ReviewEcgView evEcgView;
    ReviewEcgView evEcgView2;
    ReviewEcgView evEcgView3;
    ReviewEcgView evEcgView4;
    ReviewEcgView evEcgView5;
    ReviewEcgView evEcgView6;
    ReviewEcgView evEcgView7;
    private boolean isAlive = false;
    private Thread threadDraw;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        evEcgView = findViewById(R.id.evEcgView);
        evEcgView2 = findViewById(R.id.evEcgView2);
        evEcgView3 = findViewById(R.id.evEcgView3);
        evEcgView3.setVisibility(View.GONE);
        evEcgView4 = findViewById(R.id.evEcgView4);
        evEcgView4.setVisibility(View.GONE);
        evEcgView5 = findViewById(R.id.evEcgView5);
        evEcgView5.setVisibility(View.GONE);
        evEcgView6 = findViewById(R.id.evEcgView6);
        evEcgView6.setVisibility(View.GONE);
        evEcgView7 = findViewById(R.id.evEcgView7);
        EventBus.getDefault().register(this);
        isAlive = true;
        threadDraw = new Thread(reviewWaveContorl);
        threadDraw.start();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        isAlive = false;
        EventBus.getDefault().unregister(this);
    }

    public Activity getActivity() {
        return this;
    }

    /**
     * 判断某个界面是否在前台
     *
     * @param context   Context
     * @param className 界面的类名
     * @return 是否在前台显示
     */
    public static boolean isForeground(Context context, String className) {
        if (context == null || TextUtils.isEmpty(className))
            return false;
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> list = am.getRunningTasks(1);
        if (list != null && list.size() > 0) {
            ComponentName cpn = list.get(0).topActivity;
            if (className.equals(cpn.getClassName()))
                return true;
        }
        return false;
    }

    /**
     * 判断某个界面是否在前台
     *
     * @param activity 要判断的Activity
     * @return 是否在前台显示
     */
    public static boolean isForeground(Activity activity) {
        return isForeground(activity, activity.getClass().getName());
    }

    private Runnable reviewWaveContorl = new Runnable() {
        @Override
        public void run() {
            long num = 0;   // 100Hz数据使用
            long num2 = 0;  // 200Hz数据使用
            long num3 = 0;  // 250Hz数据使用
            long num4 = 0;  // 25Hz数据使用
            int ecgPerCount;
            int ecgPerCount2;
            int ecgPerCount3;
            int ecgPerCount4;
            int sleepTime = 15;
            Constant.reviewWaveStartTime = 0;
            long curStartTime = 0;
            long curEndTime = 0;
            DrawReviewWaveBean drawReviewWaveBean = new DrawReviewWaveBean();
            while (isAlive) {
                curStartTime = System.currentTimeMillis();
                if (Constant.reviewWaveStartTime == 0)
                    Constant.reviewWaveStartTime = System.currentTimeMillis();
                ecgPerCount = (int) (((System.currentTimeMillis() - Constant.reviewWaveStartTime) / 10) - num);
                num += ecgPerCount;
                ecgPerCount2 = (int) (((System.currentTimeMillis() - Constant.reviewWaveStartTime) / 5) - num2);
                num2 += ecgPerCount2;
                ecgPerCount3 = (int) (((System.currentTimeMillis() - Constant.reviewWaveStartTime) / 4) - num3);
                num3 += ecgPerCount3;
                ecgPerCount4 = (int) (((System.currentTimeMillis() - Constant.reviewWaveStartTime) / 40) - num4);
                num4 += ecgPerCount4;
                if (isForeground(getActivity())) {
                    drawReviewWaveBean.count = ecgPerCount;
                    drawReviewWaveBean.count2 = ecgPerCount2;
                    drawReviewWaveBean.count3 = ecgPerCount3;
                    drawReviewWaveBean.count4 = ecgPerCount4;
                    EventBus.getDefault().post(drawReviewWaveBean);
                }

                try {
                    curEndTime = System.currentTimeMillis();
                    long subTime = sleepTime - (curEndTime - curStartTime);
                    if (subTime <= 0) subTime = sleepTime;
                    Thread.sleep(subTime);
//                    TimeUnit.MILLISECONDS.sleep(subTime);
                    long wakeup = System.currentTimeMillis();
//                    System.out.println( "deal time is " + (curEndTime-curStartTime) + ", next sleep is " + subTime + ", real sleep is " + (wakeup-curEndTime));
                    Log.e(TAG, drawReviewWaveBean.toString() + ", deal time is " + (curEndTime-curStartTime) + ", next sleep is " + subTime + ", real sleep is " + (wakeup-curEndTime));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    };

    private boolean stop = false;
    private int waveSpeed = 0;
    @RequiresApi(api = Build.VERSION_CODES.O)
    @Subscribe(threadMode = ThreadMode.BACKGROUND)
    public void recvDrawWaveBean(DrawReviewWaveBean bean) {
        long startDrawTime = System.currentTimeMillis();
        if (stop) return;
        int curGain = 1;
        if (waveSpeed == 0) curGain = 1;
        else if (waveSpeed == 1) curGain = 2;
        else if (waveSpeed == 2) curGain = 3;
        bean.count *= curGain;
        bean.count2 *= curGain;
        bean.count3 *= curGain;
        bean.count4 *= curGain;
        // 绘制心电
        if (evEcgView != null) {
            evEcgView.onAlertChangeEvent(bean);
        }
        if (evEcgView2 != null) {
            evEcgView2.onAlertChangeEvent(bean);
        }
//        if (evEcgView3 != null) {
//            evEcgView3.onAlertChangeEvent(bean);
//        }
//        if (evEcgView4 != null) {
//            evEcgView4.onAlertChangeEvent(bean);
//        }
//        if (evEcgView5 != null) {
//            evEcgView5.onAlertChangeEvent(bean);
//        }
//        if (evEcgView6 != null) {
//            evEcgView6.onAlertChangeEvent(bean);
//        }
        if (evEcgView7 != null) {
            evEcgView7.onAlertChangeEvent(bean);
        }
        long endDrawTime = System.currentTimeMillis();
        long subTime = endDrawTime - startDrawTime;
//        if (subTime > 15)
        Log.e(TAG, "drawTime is " + subTime);
    }
}